var File = require('../../../class/File');
var fs = require('fs');

module.exports = {
  prefix: '/file/',
  post: {
    'upload': {
      des: {},
      multipart: true,
      method: function*(next) {
        var data = this.request.body.files.file;
        var result = yield new File(data).save();
        this.body = result;
      }
    },
    'upload/:folder': {
      multipart: true,
      method: function*() {
        var folder = this.params.folder;

        var data = this.request.body.files.file;

        data.folder = folder;

        var result = yield new File(data).save();

        this.body = result;
      }
    }
  },
  get: {
    'list': {
      method: function*() {
        var query = this.request.query;

        var result = yield File.list(query);

        this.body = result;
      }
    },
    'list/:folder': {
      method: function*() {
        var folder = this.params.folder;
        // console.log(folder);

        var query = this.request.query;

        var result = yield File.list(query, folder);

        this.body = result;
      }
    },
    'download/:_id': {
      method: function*() {
        var _id = this.params._id;

        var result = yield File.getDownloadFile(_id);

          // header("Content-type: text/plain");
          // header("Accept-Ranges: bytes");
          // header("Content-Disposition: attachment; filename=".$filename);
          // header("Cache-Control: must-revalidate, post-check=0, pre-check=0" );
          // header("Pragma: no-cache" );
          // header("Expires: 0" );
          // exit($str);

        this.set('Content-type', result.mimetype || result.type);
        // this.type = result.mimetype;
        this.set('Accept-Ranges', 'bytes');
        this.set('Content-Disposition', `attachment; filename=${encodeURIComponent(result.name)}`);
        this.set('Pragma', 'no-cache');


        this.body = fs.createReadStream(result.path);
      }
    }
  }
};
